package com.example.easybuy.controller;


import com.example.easybuy.pojo.EasybuyOrderDetail;
import com.example.easybuy.pojo.EasybuyProduct;
import com.example.easybuy.service.EasybuyOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张子晨
 * @since 2021-03-12
 */
@RestController
@RequestMapping("/easybuyOrderDetail")
public class EasybuyOrderDetailController {

    @Autowired
    EasybuyOrderDetailService easybuyOrderDetailService;

    @Autowired
    RedisTemplate redisTemplate;

    //生成订单明细
    @RequestMapping("/addOrderDetail")
    public int addOrderDetail(String orderId, String userId) {

        //获取Redis中的购物车
        Map<String, Object> redisMap = (Map<String, Object>) redisTemplate.opsForValue().get("car" + userId);

        Map<String, Integer> stockMap = (Map<String, Integer>) redisMap.get("stockMap");

        List<EasybuyProduct> productList = (List<EasybuyProduct>) redisMap.get("productList");

        Map<String, Object> map = new HashMap<>();

        EasybuyOrderDetail easybuyOrderDetail = null;

        int i = 0;
        for (String key : stockMap.keySet()) {
            map.put("orderId", orderId);
            map.put("productId", Integer.parseInt(key));
            map.put("quantity", stockMap.get(key));
            for (EasybuyProduct product : productList) {
                if (product.getId() == Integer.parseInt(key)) {
                    map.put("cost", stockMap.get(key) * product.getPrice());
                    i = easybuyOrderDetailService.addOrderDetail(map);
                }
            }
        }
        redisTemplate.delete(redisTemplate.keys("car" + userId));
        redisTemplate.delete(redisTemplate.keys("buyCar" + userId));
        return i;
    }
}

